<!--
  去入库
-->
<template>
	<a-modal :title="disabled ? '入库单详情' : '去入库'" :width="1600" :visible="visible" :confirmLoading="confirmLoading"
		@ok="handleSubmit" @cancel="handleCancel" :okText="'确认入库'" :footer="disabled ? null : undefined">
		<div style="position: absolute;bottom: 15px;left: 40px;" v-if="!disabled">
			<a-button type="primary" @click="finish">入库完结</a-button>
		</div>
		<a-card :bordered="false">
			<div class="table-page-search-wrapper">
				<a-form layout="inline" :form="form">
					<a-row :gutter="48">
						<a-col :md="12" :sm="24">
							<a-form-item label="入库单号">
								<a-input :disabled="disabled" v-decorator="['orderNumber']" placeholder="请输入入库单号" />
							</a-form-item>
						</a-col>
						<a-col :md="12" :sm="24">
							<a-form-item label="入库时间">
								<a-date-picker show-time :disabled="disabled" value-format="YYYY-MM-DD HH:mm:ss"
									format="YYYY-MM-DD HH:mm:ss"
									v-decorator="['rkTime', { rules: [{ required: true, message: '请选择入库时间!' }] }]"
									placeholder="请选择入库时间" />
							</a-form-item>
						</a-col>
						<a-col :md="12" :sm="24">
							<a-form-item label="备注">
								<a-textarea :disabled="disabled" v-decorator="['remark']" placeholder="请输入备注" />
							</a-form-item>
						</a-col>
						<a-col :md="12" :sm="24">
							<a-form-item label="入库凭证">
								<div v-if="!disabled">
									<a-input v-show="false" :disabled="disabled" placeholder="请上传图片" v-decorator="['file']" />
									<fc-upload :file-list="fileList" :disabled="disabled"
										:handle-file-list-string-change="handleFileListStringChange" />
								</div>
								<div v-else>
									<a-input v-show="false" :disabled="disabled" placeholder="请上传图片" v-decorator="['file']" />
									<fc-upload :file-list="fileList" v-if="fileList.length != 0" :disabled="disabled"
										:handle-file-list-string-change="handleFileListStringChange" />
									<div v-else>暂无凭证</div>
								</div>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<a-table ref="table" size="default" :columns="columns" :data-source="filteredData" :alert="true"
				:rowKey="(record) => record.code"
				:rowSelection="null && { selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :showPagination="false">
				<!-- <span slot="image" slot-scope="text">
					<image-preview :images="text" />
				</span> -->
				<span slot="image" slot-scope="text,record">
					<image-preview1 :images="text" :imageUrl="record.material.imageUrl" />
				</span>
				<span slot="rukuNumber" slot-scope="text,record">
					<a-input-number @change="inputNumberChange($event, record)" v-model="record.rukuNumber" :min="0"
						style="width: 67px;" />
					<!-- <a-input-number v-if="$util.getUrlParam($route.path).materialType == '1473944389062504450'" v-model="record.rukuNumber" :min="0" style="width: 67px;" />
					<a-input-number v-else v-model="record.rukuNumber" :max="record.number - record.completedNumber < 0 ? 0 : record.number - record.completedNumber" :min="0" style="width: 67px;" /> -->
				</span>
				<span slot="remark" slot-scope="text,record">
					<a-textarea v-model="record.remark" />
				</span>
			</a-table>
		</a-card>
	</a-modal>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { STable } from '@/components'
import { page, del, add } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import inStoreSourceForm from '@/views/main/emsordermaterial/purchaseOrder/emsInStoreSourceForm'
import FcUpload from '@/components/FCUpload/FcUpload'
import { page as emsOrderMaterialManagePage } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import { addSimple, addAllType, endRkCGOrder } from '@/api/modular/main/emsorder/emsOrderManage'
import moment from 'moment'
export default {
	components: {
		STable,
		FcUpload,
		inStoreSourceForm,
	},

	data() {
		return {
			title: null,
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			filteredData: [],
			form: this.$form.createForm(this),
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			visible: false,
			confirmLoading: false,
			emsOrder: null,
			viewStateEnum: {
				normalSupplier: 'normalSupplier',
				primarySupplier: 'primarySupplier',
				purchaseOrderEnd: 'purchaseOrderEnd', //这个应该没有，UI和normalSupplier长的一样
			},
			viewState: '',
			extra: {},
			fileList: [],
			disabled: false,
			columns: [],
		}
	},
	computed: {
		token() {
			return Vue.ls.get(ACCESS_TOKEN)
		},
	},
	methods: {
		inputNumberChange(e, data) {
			let arr = ['1473944715475824641', '1473944389062504450']
			if (e < 0) {
				data.rukuNumber = 0
			}
			let num;
			if (arr.includes(this.$util.getUrlParam(this.$route.path).materialType)) {
				num = (Math.round(data.number * 0.1) + data.number) - data.completedNumber
			} else {
				num = data.number - data.completedNumber;
			}
			data.rukuNumber = e > num ? num : e;
		},
		moment,
		show(record, extra) {
			this.visible = true
			this.emsOrder = record;
			this.disabled = false;
			setTimeout(() => {
				this.form.setFieldsValue({
					rkTime: this.moment(new Date().toLocaleDateString(), 'YYYY-MM-DD HH:mm:ss')
				})
			}, 200);
			this.columns = [
				{
					title: '序号', width: '80px',
					align: 'center',
					customRender: (text, record, index) => `${index + 1}`,
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '物料名称',
					dataIndex: 'materialName'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber',
					scopedSlots: { customRender: 'materialModelNumber' }
				},
				{
					title: '图片',
					dataIndex: 'image',
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '采购数量',
					dataIndex: 'number',
				},
				{
					title: '已入库数量',
					dataIndex: 'completedNumber',
				},
				{
					title: '待入库数量',
					dataIndex: '',
					customRender: (text, record, index) => record.number - record.completedNumber < 0 ? 0 : record.number - record.completedNumber,
				},
				{
					title: '入库数量',
					// dataIndex: 'rukuNumber',
					scopedSlots: { customRender: 'rukuNumber' }
				},
				{
					title: '备注',
					dataIndex: 'remark',
					scopedSlots: { customRender: 'remark' }
				},
			];
			emsOrderMaterialManagePage({
				pageSize: -1,
				materialType: this.$util.getUrlParam(this.$route.path).materialType,
				orderId: record.orderId,
				// filterType:1,
				sourceOrderMaterialId: 0,
			}).then(res => {
				console.log(res);
				this.filteredData = res.data.rows.map(val => {
					return {
						...val,
						// rukuNumber: val.number - val.completedNumber >= 0 ? val.number - val.completedNumber : 0,
						rukuNumber: 0,
					}
				});
				console.log("this.filteredData---", this.filteredData);

			})
		},
		readonly(record) {
			emsOrderMaterialManagePage({
				pageSize: -1,
				materialType: this.$util.getUrlParam(this.$route.path).materialType,
				orderId: record.orderId,
			}).then(res => {
				console.log(res);
				this.filteredData = res.data.rows.map(val => {
					return {
						...val,					
						rukuNumber: 0,
					}
				});
				console.log("this.filteredData---", this.filteredData);

			})
			this.visible = true
			this.emsOrder = record;
			setTimeout(() => {
				this.form.setFieldsValue(record)
			}, 200);
			this.columns = [
				{
					title: '序号', width: '80px',
					align: 'center',
					customRender: (text, record, index) => `${index + 1}`,
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '物料名称',
					dataIndex: 'materialName'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber',
					scopedSlots: { customRender: 'materialModelNumber' }
				},
				{
					title: '图片',
					dataIndex: 'image',
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '采购数量',
					dataIndex: 'productRecord.number',
				},
				{
					title: '已入库数量',
					dataIndex: 'productRecord.completedNumber',
				},
				{
					title: '待入库数量',
					dataIndex: '',
					customRender: (text, record, index) => record.productRecord.number - record.productRecord.completedNumber < 0 ? 0 : record.productRecord.number - record.productRecord.completedNumber,
				},
				{
					title: '入库数量',
					dataIndex: 'number',
					// scopedSlots: { customRender: 'rukuNumber' }
				},
			]
			this.disabled = true;
			if (!record.file) {
				this.fileList = [];
				return
			}
			this.fileList = record.file.split(',').map(fileID => {
				return {
					uid: fileID,
					name: fileID,
					status: 'done',
					url: `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${fileID}&token=${this.token}`,
					fileID: fileID
				}
			})

		},
		handleFileListStringChange(fileListString) {
			// console.debug(`fileListString: ${fileListString}`)
			this.form.setFieldsValue({ file: fileListString })
		},
		handleOk() {
			this.$refs.table.refresh()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		finish() {
			let orderMaterials = this.filteredData
			let index = orderMaterials.filter(value => value.number - value.completedNumber > 0);
			let that = this;
			if (index.length > 0) {
				this.$confirm({
					content: '当前采购单存在实收数量小于采购数物料，请核对后再操作',
					centered: true,
					onOk() {
						endRkCGOrder({
							orderId: that.emsOrder.orderId,
						}).then(res => {
							if (res.code == 200) {
								that.$message.success("操作成功");
								that.visible = false;
								that.$emit("ok");
								return false;
							}
						})
					},
					cancelText: '取消',
					okText: '确定完结',
					onCancel() {
						// that.visible = false;
						// that.$emit("ok");
						return false;
					},
				});
			} else {
				this.$confirm({
					content: '是否确认完结采购单',
					centered: true,
					onOk() {
						endRkCGOrder({
							orderId: that.emsOrder.orderId,
						}).then(res => {
							if (res.code == 200) {
								that.$message.success("操作成功");
								that.visible = false;
								that.$emit("ok");
								return false;
							}
						})
					},
					cancelText: '取消',
					okText: '确定',
					onCancel() {
						// that.visible = false;
						// that.$emit("ok");
					},
				});
			}
			console.log(orderMaterials);
			console.log(index);
		},
		handleSubmit() {
			const { form: { validateFields } } = this
			validateFields((errors, values) => {
				if (!errors) {
					console.log("进入");

					let orderMaterials = this.filteredData
					let index = orderMaterials.filter(value => !value.rukuNumber && value.rukuNumber != 0)
					if (index.length > 0) {
						this.$message.error("请填写入库数量");
						return
					}
					this.confirmLoading = true;
					let orderMaterialParams = orderMaterials.map(value => {
						return {
							orderMaterialId: '',
							orderId: '',
							sourceOrderId: value.orderId,
							sourceOrderMaterialId: value.orderMaterialId,
							bomId: '0',
							materialId: value.materialId,
							number: value.rukuNumber,//入库数量
							extraNumber: 0,
							completedNumber: value.number,
							executeStatus: this.$businessEnum.EXECUTE_STATUS_ENUM.COMPLETED.id,
							executeProgress: 100,
							file: '',
							remark: value.remark,
							markAbnormal: '0',
							status: '',
							createTime: '',
							createUser: '',
							updateTime: '',
							updateUser: '',
						}
					})
					let orderParam = {
						orderId: '',
						sourceOrderId: this.emsOrder.orderId,
						orderParentId: '',
						orderPids: '',
						orderNumber: values.orderNumber,
						orderType: this.$businessEnum.ORDER_TYPE_ENUM.inOrder.id,
						orgId: '',
						targetOrgId: '',
						isOverseasStore: '',
						countryCode: '',
						file: values.file,
						remark: values.remark,
						executeStatus: this.$businessEnum.EXECUTE_STATUS_ENUM.COMPLETED.id,
						executeProgress: 100,
						issueTime: '',
						estimateCompletionTime: '',
						receiveTime: '',
						status: '',
						createTime: '',
						createUser: '',
						updateTime: '',
						updateUser: '',
						orderMaterials: orderMaterialParams,
						rkTime: typeof values.rkTime == 'string' ? values.rkTime : values.rkTime.format('YYYY-MM-DD HH:mm:ss'),
						materialPoolIds: null,
					}
					console.log(values);

					console.log("this.filteredData", this.filteredData);
					// return
					let that = this;

					addAllType(orderParam).then(res => {
						console.log(res);
						if (res.code == 200) {
							this.$message.success("操作成功");
							let index1 = orderMaterials.filter(value => value.number - value.completedNumber - value.rukuNumber <= 0);
							console.log(index1);

							if (index1.length == orderMaterials.length) {
								this.$confirm({
									content: '采购单所有物料全部入库，是否完结采购单？',
									centered: true,
									onOk() {
										endRkCGOrder({
											orderId: that.emsOrder.orderId,
										}).then(res => {
											if (res.code == 200) {
												that.$message.success("操作成功");
												that.visible = false;
												that.confirmLoading = false;
												that.$emit("ok");
												return false;
											}
										})
									},
									cancelText: '不完结',
									okText: '确定完结',
									onCancel() {
										that.visible = false;
										that.confirmLoading = false;
										that.$emit("ok");
									},
								});
								return;
							} else {
								this.visible = false;
								this.confirmLoading = false;
								this.$emit("ok");
							}
						}
					})
					return
				} else {
					this.confirmLoading = false
				}
			})
			let order = this.emsOrder

		},
		handleCancel() {
			this.visible = false
		},
		onEmsMaterialIndex1Selected(materialRow) {
			// console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
			// debugger
			let { materialId, materialName, materialCode, materialType, costPrice } = materialRow
			// 需要调用接口往订单中添加物料
			let _emsOrder = Object.assign({}, this.emsOrder)
			_emsOrder.orderMaterials = []
			let orderMaterial = {
				orderMaterialId: '',
				orderId: _emsOrder.orderId,
				bomId: '0',  // 单独选择原料时没有BOMID
				materialId: materialId,
				number: 1,
				completedNumber: 0,
				executeStatus: '0',
				executeProgress: '0',
				status: '0',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
			}
			_emsOrder.orderMaterials.push(orderMaterial)
			add(orderMaterial).then(res => {
				if (res.success) {
					this.$message.success('新增成功')
					// this.handleCancel()
					// this.$emit('ok', values)
					this.$refs.table.refresh()
				} else {
					this.$message.info('新增失败：' + res.message)
				}
			})
			// 然后刷新table控件
		},
		imageURLFormat(text) {
			return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
		}
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
